<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="产品编号" prop="productCode">
        <el-input
          v-model="queryParams.productCode"
          placeholder="请输入产品编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品类型" prop="parentTypeId">
          <el-cascader
            v-model="queryParams.productTypeId"
            :options="producttypeOptions"
            :props="{ 
              value: 'typeId', 
              label: 'typeName',
              checkStrictly: true,
              emitPath: false
            }"
            clearable
            placeholder="请选择父类型"
          />
        </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:product:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:product:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:product:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:product:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload"
          size="mini"
          @click="handleImport"
          v-hasPermi="['system:product:importForm']"
        >导入</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="productList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="产品编号" align="center" prop="productCode" width="120" />
      <el-table-column label="产品名称" align="center" prop="name" />
      <el-table-column label="型号" align="center" prop="model" />
      <el-table-column label="产品类型" align="center" prop="productTypeName" width="80"/>
      <el-table-column label="产品图片" align="center" prop="pics" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.pics" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="成本价" align="center" prop="basePrice" width="80">
        <template slot-scope="scope">
          {{scope.row.basePrice}}元
        </template>
      </el-table-column>
      <el-table-column label="销售价" align="center" prop="salePrice" width="80">
        <template slot-scope="scope">
          {{scope.row.salePrice}}元
        </template>
      </el-table-column>
      <el-table-column label="库存数量" align="center" prop="storeCount" width="80"/>
      <el-table-column label="内容介绍" align="center" prop="comment">
        <template slot-scope="scope">
          <div style="max-height: 60px; overflow: hidden; text-overflow: ellipsis; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical;">
            {{scope.row.comment}}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:product:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:product:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改产品信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="产品编号" prop="productCode">
          <el-input v-model="form.productCode" placeholder="请输入产品编号" />
        </el-form-item>
        <el-form-item label="产品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入产品名称" />
        </el-form-item>
        <el-form-item label="型号" prop="model">
          <el-input v-model="form.model" placeholder="请输入型号" />
        </el-form-item>
        <el-form-item label="产品类型" prop="parentTypeId">
          <el-cascader
            v-model="form.productTypeId"
            :options="producttypeOptions"
            :props="{ 
              value: 'typeId', 
              label: 'typeName',
              checkStrictly: true,
              emitPath: false
            }"
            clearable
            placeholder="请选择产品类型"
          />
        </el-form-item>
        <el-form-item label="产品图片" prop="pics">
          <image-upload v-model="form.pics"/>
        </el-form-item>
        <el-form-item label="成本价" prop="basePrice">
        <el-input v-model="form.basePrice" placeholder="请输入成本价">
          <template slot="append">元</template>
        </el-input>
      </el-form-item>
      <el-form-item label="销售价" prop="salePrice">
        <el-input v-model="form.salePrice" placeholder="请输入销售价">
          <template slot="append">元</template>
        </el-input>
      </el-form-item>
        <el-form-item label="库存数量" prop="storeCount">
          <el-input v-model="form.storeCount" placeholder="请输入库存数量" />
        </el-form-item>
        <el-form-item label="内容介绍" prop="comment">
          <el-input v-model="form.comment" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 导入对话框 -->
    <el-dialog :title="importForm.title" :visible.sync="importForm.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="importForm.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProduct, getProduct, delProduct, addProduct, updateProduct } from "@/api/system/product";
import { listProducttype, getProducttype, delProducttype, addProducttype, updateProducttype } from "@/api/system/producttype";
export default {
  name: "Product",
  data() {
    return {
      // 导入参数
      importForm: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
      },
      upload: {
        // 是否显示上传中
        isUploading: false,
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 产品信息表格数据
      productList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productCode: null,
        name: null,
        productTypeId: null,
      },
      // 查询参数
      typeQueryParams: {
        pageNum: 1,
        pageSize: 1000,
        productCode: null,
        name: null,
        productTypeId: null,
      },
      // 表单参数
      form: {},
      // 添加树形选择器选项
      producttypeOptions: [], 
      // 表单校验
      rules: {
        name: [
          { required: true, message: "产品名称不能为空", trigger: "blur" }
        ],
        productTypeId: [
          { required: true, message: "产品类型不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getTypeList();
    this.upload.url = process.env.VUE_APP_BASE_API + "/system/product/importData";
    this.upload.headers = { "Authorization": "Bearer " + this.$store.state.user.token };
  },
  methods: {
    /** 导入按钮操作 */
    handleImport() {
      this.importForm.title = "产品导入";
      this.importForm.open = true;
      this.$nextTick(() => {
        this.$refs.upload.clearFiles();
      });
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('system/product/importTemplate', {}, `产品导入模板_${new Date().getTime()}.xlsx`);
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.importForm.open = false;
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /** 查询产品信息列表 */
    getList() {
      this.loading = true;
      listProduct(this.queryParams).then(response => {
        this.productList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    /** 查询用户信息列表 */
    getTypeList() {
      this.loading = true;
      listProducttype(this.typeQueryParams).then(response => {
        this.producttypeOptions = this.buildTree(response.rows);
        this.total = response.total;
        this.loading = false;
      });
    },
    // 添加构建树形结构的方法
    buildTree(data) {
      const map = {};
      const tree = [];
      data.forEach(item => {
        map[item.typeId] = { ...item, children: [] };
      });
      data.forEach(item => {
        if (item.parentTypeId && map[item.parentTypeId]) {
          map[item.parentTypeId].children.push(map[item.typeId]);
        } else {
          tree.push(map[item.typeId]);
        }
      });
      return tree;
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        productId: null,
        productCode: null,
        name: null,
        productTypeId: null,
        pics: null,
        basePrice: null,
        salePrice: null,
        storeCount: null,
        comment: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.productId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      // 生成基于日期时间的产品编号 CP+年月日时分秒
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      const seconds = String(now.getSeconds()).padStart(2, '0');
      
      this.form.productCode = `CP${year}${month}${day}${hours}${minutes}${seconds}`;
      this.open = true;
      this.title = "添加产品信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const productId = row.productId || this.ids
      getProduct(productId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改产品信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.productId != null) {
            updateProduct(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProduct(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const productIds = row.productId || this.ids;
      this.$modal.confirm('是否确认删除产品信息编号为"' + productIds + '"的数据项？').then(function() {
        return delProduct(productIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/product/export', {
        ...this.queryParams
      }, `product_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
